﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LibFriesland_Campina_CRM;
using System.Data;
using System.Collections;

public partial class UserControls_UCAttendanaceTracking : System.Web.UI.UserControl
{

    #region Thuoc tinh
    private string by_shop
    {
        get 
        {
            if (ViewState["_by_shop"] == null)
                return "";
            return ViewState["_by_shop"].ToString(); 
        }
        set { ViewState["_by_shop"] = value; }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        ViewState["naList"] = new ArrayList();
        if (ViewState["viewTracking"] == null)
            ViewState["viewTracking"] = "true";
        ViewState["by_sup"] = Request.Form["ctl00$ContentPlaceHolder1$cboSupervisor"];
        ViewState["dateTracking"] = Request.Form["ctl00$ContentPlaceHolder1$dateTracking"];
        if (!IsPostBack || ViewState["viewTracking"].ToString() == "true" || ViewState["by_sup"].ToString() != ViewState["pre_by_sup"].ToString() || ViewState["pre_dateTracking"].ToString() != ViewState["dateTracking"].ToString())
        {
            try
            {
                ViewState["viewTracking"] = false;
                ViewState["pre_by_sup"] = ViewState["by_sup"];
                ViewState["pre_dateTracking"] = ViewState["dateTracking"];

                hdBy_manager.Value = ((BizAccount)Session["account"]).username;
                hdBy_sup.Value = ViewState["by_sup"].ToString();
                hdDate_tracking.Value = ViewState["dateTracking"].ToString();

                //CurrentPage = 0;
                databindTrackingStatistics();
                //databindTrackingDetail();
                //databindCboShop();
            }
            catch(Exception ex)
            {
                ViewState["viewTracking"] = null;
            }
        }
    }

    #region Lien ket du lieu
    private void databindTrackingStatistics()
    {
        string by_sup = ViewState["by_sup"].ToString();
        List<BizNaShop> naShifts = BizNaShop.getShiftNAbySup(by_sup);
        naShifts.Sort(NaShopSort.byNaComparison);
        repeaterTrackingStatistics.DataSource = naShifts;
        repeaterTrackingStatistics.DataBind();

    }
    private void databindTrackingDetail()
    {
        string by_sup = ViewState["by_sup"].ToString();
        List<BizNaShop> naShifts = new List<BizNaShop>();
        if (by_shop == "")
        {
            naShifts = BizNaShop.getShiftNAbySup(by_sup);
            naShifts.Sort(NaShopSort.byShopComparison);
        }
        else
            naShifts = BizNaShop.getShiftNAbyShopSup(by_shop, by_sup);

        PagedDataSource page = new PagedDataSource();
        page.DataSource = naShifts;
        page.AllowPaging = true;
        page.PageSize = 3;
        page.CurrentPageIndex = CurrentPage;
        ViewState["TotalPages"] = page.PageCount;
        ViewState["count"] = 3;
        this.lbPrev.Visible = !page.IsFirstPage;
        this.lbNext.Visible = !page.IsLastPage;
        this.lbFirst.Visible = !page.IsFirstPage;
        this.lbLast.Visible = !page.IsLastPage;

        repeaterTrackingDetail.DataSource = page;
        repeaterTrackingDetail.DataBind();
        
        this.doPaging();
    }
    private void databindCboShop()
    {
        string by_sup = ViewState["by_sup"].ToString();
        List<BizShop> shops = BizNaShop.getShopNAbySup(by_sup);
        cboShop.DataTextField = "name";
        cboShop.DataValueField = "shop_charid";
        cboShop.DataSource = shops;
        cboShop.DataBind();

        ListItem item = new ListItem("Tất cả ------", "");
        cboShop.Items.Add(item);
        cboShop.SelectedIndex = cboShop.Items.Count - 1;
    }
    #endregion

    protected void repeaterTrackingDetail_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        Label lbBy_na = (Label)(e.Item.FindControl("lbBy_na"));
        HiddenField hdBy_shift = (HiddenField)(e.Item.FindControl("hdBy_shift"));
        HiddenField hdBy_shop = (HiddenField)(e.Item.FindControl("hdBy_shop"));

        //Lay thong tin chi tiet cham cong cua NA theo tung shop, ca
        DateTime dateTracking = Convert.ToDateTime(Thuvien.myConvertStringToShortDate(ViewState["dateTracking"].ToString()));
        List<BizAttendanceTracking> attendaceTrackingList = BizAttendanceTracking.getFullAttendanceTrackingbyNA(lbBy_na.Text, dateTracking, hdBy_shop.Value, hdBy_shift.Value);

        #region Hien thi thoi gian cham cong
        ////Dau gio
        Label lbStarttime_gps = (Label)(e.Item.FindControl("lbStarttime_gps"));
        Label lbStarttime_phone = (Label)(e.Item.FindControl("lbStarttime_phone"));
        Label lbStarttime_system = (Label)(e.Item.FindControl("lbStarttime_system"));
        BizAttendanceTracking starttimeTracking = attendaceTrackingList.Find(p => p.by_time_point == "1");
        displayTrackingTime(starttimeTracking, lbStarttime_gps, lbStarttime_phone, lbStarttime_system);

        ////Giua gio
        Label lbMiddletime_gps = (Label)(e.Item.FindControl("lbMiddletime_gps"));
        Label lbMiddletime_phone = (Label)(e.Item.FindControl("lbMiddletime_phone"));
        Label lbMiddletime_system = (Label)(e.Item.FindControl("lbMiddletime_system"));
        BizAttendanceTracking middletimeTracking = attendaceTrackingList.Find(p => p.by_time_point == "2");
        displayTrackingTime(middletimeTracking, lbMiddletime_gps, lbMiddletime_phone, lbMiddletime_system);

        ////Cuoi gio
        Label lbEndtime_gps = (Label)(e.Item.FindControl("lbEndtime_gps"));
        Label lbEndtime_phone = (Label)(e.Item.FindControl("lbEndtime_phone"));
        Label lbEndtime_system = (Label)(e.Item.FindControl("lbEndtime_system"));
        BizAttendanceTracking endtimeTracking = attendaceTrackingList.Find(p => p.by_time_point == "3");
        displayTrackingTime(endtimeTracking, lbEndtime_gps, lbEndtime_phone, lbEndtime_system);
        #endregion

        #region Hien thi trang thai cham cong
        ////Dau gio
        Label lbStarttime_gps_status = (Label)(e.Item.FindControl("lbStarttime_gps_status"));
        Label lbStarttime_ontime_status = (Label)(e.Item.FindControl("lbStarttime_ontime_status"));
        HyperLink hyperStarttime_Latlng = (HyperLink)(e.Item.FindControl("hyperStarttime_Latlng"));
        displayTrackingStatus(starttimeTracking, lbStarttime_gps_status, lbStarttime_ontime_status, hyperStarttime_Latlng, lbBy_na.Text);

        ////Giua gio
        Label lbMiddletime_gps_status = (Label)(e.Item.FindControl("lbMiddletime_gps_status"));
        Label lbMiddletime_ontime_status = (Label)(e.Item.FindControl("lbMiddletime_ontime_status"));
        HyperLink hyperMiddletime_Latlng = (HyperLink)(e.Item.FindControl("hyperMiddletime_Latlng"));
        displayTrackingStatus(middletimeTracking, lbMiddletime_gps_status, lbMiddletime_ontime_status, hyperMiddletime_Latlng, lbBy_na.Text);

        ////Cuoi gio
        Label lbEndtime_gps_status = (Label)(e.Item.FindControl("lbEndtime_gps_status"));
        Label lbEndtime_ontime_status = (Label)(e.Item.FindControl("lbEndtime_ontime_status"));
        HyperLink hyperEndtime_Latlng = (HyperLink)(e.Item.FindControl("hyperEndtime_Latlng"));
        displayTrackingStatus(endtimeTracking, lbEndtime_gps_status, lbEndtime_ontime_status, hyperEndtime_Latlng, lbBy_na.Text);
        #endregion

        #region Hien thi action cua Supervisor
        ////Dau gio
        Label lbStarttime_action = (Label)(e.Item.FindControl("lbStarttime_action"));
        displayTrackingActionbySup(starttimeTracking, lbStarttime_action, lbStarttime_ontime_status, lbStarttime_gps_status);

        ////Giua gio
        Label lbMiddletime_action = (Label)(e.Item.FindControl("lbMiddletime_action"));
        displayTrackingActionbySup(middletimeTracking, lbMiddletime_action, lbMiddletime_ontime_status, lbMiddletime_gps_status);

        ////Cuoi gio
        Label lbEndtime_action = (Label)(e.Item.FindControl("lbEndtime_action"));
        displayTrackingActionbySup(endtimeTracking, lbEndtime_action, lbEndtime_ontime_status, lbEndtime_gps_status);
        #endregion
    }
    protected void repeaterTrackingStatistics_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        Label lbNa_charid = (Label)(e.Item.FindControl("lbNa_charid"));
        Label lbNa_name = (Label)(e.Item.FindControl("lbNa_name"));
        
        //Kiem tra dong tiep co cung mot NA
        ArrayList temp = (ArrayList)ViewState["naList"];
        if (temp.IndexOf(lbNa_charid.Text) == -1)
        {
            temp.Add(lbNa_charid.Text);
            lbNa_charid.Visible = true;
            lbNa_name.Visible = true;
            ViewState["naList"] = temp;
        }
        else
        {
            lbNa_charid.Visible = false;
            lbNa_name.Visible = false;
        }
        
        HiddenField hdShop_charid = (HiddenField)(e.Item.FindControl("hdShop_charid"));
        HiddenField hdBy_shift = (HiddenField)(e.Item.FindControl("hdBy_shift"));
        HyperLink hyperViewDetailTracking = (HyperLink)(e.Item.FindControl("hyperViewDetailTracking"));
        DateTime dateTracking = Convert.ToDateTime(Thuvien.myConvertStringToShortDate(ViewState["dateTracking"].ToString()));

        hyperViewDetailTracking.NavigateUrl = String.Format("~/ViewAttendanceTrackingDetail.aspx?by_na={0}&by_shop={1}&by_shift={2}&dateTracking={3}", lbNa_charid.Text, hdShop_charid.Value, hdBy_shift.Value, ViewState["dateTracking"].ToString());
        List<BizAttendanceTracking> adt = BizAttendanceTracking.getFullAttendanceTrackingbyNA(lbNa_charid.Text, dateTracking, hdShop_charid.Value, hdBy_shift.Value);

        #region Hien thi thong tin dau gio
        Label lbStarttime_ontime = (Label)(e.Item.FindControl("lbStarttime_ontime"));
        Label lbStarttime_GPS = (Label)(e.Item.FindControl("lbStarttime_GPS"));
        BizAttendanceTracking starttimeTracking = adt.Find(p=>p.by_time_point == "1");
        displayTrackingStatistics(starttimeTracking, lbStarttime_ontime, lbStarttime_GPS);
        #endregion

        #region Hien thi thong tin giua gio
        Label lbMiddletime_ontime = (Label)(e.Item.FindControl("lbMiddletime_ontime"));
        Label lbMiddletime_GPS = (Label)(e.Item.FindControl("lbMiddletime_GPS"));
        BizAttendanceTracking middletimeTracking = adt.Find(p => p.by_time_point == "2");
        displayTrackingStatistics(middletimeTracking, lbMiddletime_ontime, lbMiddletime_GPS);
        #endregion

        #region Hien thi thong tin cuoi gio
        Label lbEndtime_ontime = (Label)(e.Item.FindControl("lbEndtime_ontime"));
        Label lbEndtime_GPS = (Label)(e.Item.FindControl("lbEndtime_GPS"));
        BizAttendanceTracking endtimeTracking = adt.Find(p => p.by_time_point == "3");
        displayTrackingStatistics(endtimeTracking, lbEndtime_ontime, lbEndtime_GPS);
        #endregion
    }

    //Xu ly luu Action cua Manager doi voi Supervisor
    protected void btnSaveAction_Click(object sender, EventArgs e)
    {
        string bySup = ViewState["by_sup"].ToString();
        string byManager = ((BizAccount)Session["account"]).username;
        DateTime datetimeAction = Convert.ToDateTime(Thuvien.myConvertStringToShortDate(ViewState["dateTracking"].ToString()));
        DateTime datetimeMonitoring = DateTime.Now;
        string actionMonitoring = txtAction.Text;
        string commentMonitoring = txtComment.Text;
        BizManagerMonitoring managerMonitoring = new BizManagerMonitoring(-1, datetimeAction, datetimeMonitoring, actionMonitoring, commentMonitoring, bySup, byManager);
        int status = managerMonitoring.addManagerMonitoring();
        if (status == 1)
            Response.Write("<script>alert('" + "Thêm ghi chú thành công !" + "')</script>");
        else
            Response.Write("<script>alert('" + "Không thể thêm ghi chú !" + "')</script>");
    }

    #region Cac ham xu ly hien thi thong tin cham cong
    //Hien thi thong tin thoi gian cham cong
    private void displayTrackingTime(BizAttendanceTracking adt, Label lbTime_gps, Label lbTime_phone, Label lbTime_system)
    {
        if (adt != null)
        {
            DateTime? datetimeGPS = adt.datetime_gps;
            if (datetimeGPS != null)
                lbTime_gps.Text = Convert.ToDateTime(datetimeGPS).ToString("dd/MM/yyyy HH:mm:ss");
            else
                lbTime_gps.Text = "-";
            lbTime_phone.Text = Convert.ToDateTime(adt.datetime_phone).ToString("dd/MM/yyyy HH:mm:ss");
            lbTime_system.Text = Convert.ToDateTime(adt.datetime_system).ToString("dd/MM/yyyy HH:mm:ss");
        }
        else
        {
            lbTime_gps.Text = "N/A";
            lbTime_phone.Text = "N/A";
            lbTime_system.Text = "N/A";
        }
    }

    //Hien thi thong tin trang thai cham cong
    private void displayTrackingStatus(BizAttendanceTracking adt, Label lbGps_status, Label lbOntime_status, HyperLink hyperLatlng, string pBy_na)
    {
        if (adt != null)
        {
            if (adt.latitude != 0 || adt.longitude != 0) //Neu lay duoc toa do GPS
            {
                if (adt.getLatlngStatus() == true)
                {
                    lbGps_status.ForeColor = System.Drawing.Color.Blue;
                    lbGps_status.Text = "Có";
                }
                else
                {
                    lbGps_status.ForeColor = System.Drawing.Color.Red;
                    lbGps_status.Text = "Không";
                }
                hyperLatlng.NavigateUrl = String.Format("~/MapWithClickablePushpins.aspx?latGPS={0}&longGPS={1}&type={2}", adt.latitude, adt.longitude, "viewTrackingPoint");
            }
            else
            {
                lbGps_status.ForeColor = System.Drawing.Color.Red;
                lbGps_status.Text = "N/A";
                hyperLatlng.Visible = false;
            }
 
            int timeStatus = adt.getTimeStatus();
            if (timeStatus == 1)
            {
                lbOntime_status.ForeColor = System.Drawing.Color.Blue;
                lbOntime_status.Text = "Có";
            }
            else
            {
                lbOntime_status.ForeColor = System.Drawing.Color.Red;
                lbOntime_status.Text = "Không";
            }
        }
        else
        {
            lbGps_status.Text = "N/A";
            lbOntime_status.Text = "N/A";
            hyperLatlng.Visible = false;
        }
    }

    //Hien thi thong tin action cua Supervisor
    private void displayTrackingActionbySup(BizAttendanceTracking adt, Label lbAction, Label lbOntime_status, Label lbGPS_status)
    {
        if (adt != null)
        {
            if (adt.comment_monitoring != "")
            {
                lbAction.ForeColor = System.Drawing.Color.Blue;
                lbAction.Text = "Có";
            }
            else
            {
                if (lbOntime_status.Text == "Không" || lbGPS_status.Text == "Không")
                    lbAction.ForeColor = System.Drawing.Color.Red;
                lbAction.Text = "Không";
            }
        }
        else
            lbAction.Text = "N/A";
    }
    
    //Loc thong tin cham cong theo Shop
    protected void cboShop_SelectedIndexChanged(object sender, EventArgs e)
    {
        CurrentPage = 0;
        by_shop = cboShop.SelectedValue;
        databindTrackingDetail();
    }
    #endregion

    #region Cac ham xu ly hien thi thong tin thong ke cham cong
    //Hien thi thong tin thong ke cham cong
    private void displayTrackingStatistics(BizAttendanceTracking adt, Label lbOntime, Label lbGPS)
    {
        if (adt != null)
        {
            if (adt.getTimeStatus() == 1)
            {
                lbOntime.Text = "v";
            }
            else
            {
                lbOntime.ForeColor = System.Drawing.Color.Red;
                lbOntime.Text = "x";
            }

            if (adt.longitude != 0 || adt.latitude != 0) //Neu lay duoc toa do
            {
                if (adt.getLatlngStatus() == true)
                    lbGPS.Text = "v";
                else
                {
                    lbGPS.ForeColor = System.Drawing.Color.Red;
                    lbGPS.Text = "x";
                }
            }
            else
            {
                //lbGPS.Text = "N/A";
            }
        }
        else
        {
            //lbOntime.Text = lbGPS.Text = "N/A";
        }
    }
    #endregion

    #region Xu ly phan trang
    private void doPaging()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");
        fistIndex = CurrentPage - 5;
        if (CurrentPage > 5)
        {
            lastIndex = CurrentPage + 5;
        }
        else
        {
            lastIndex = 10;
        }
        if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
        {
            lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
            fistIndex = lastIndex - 10;
        }
        if (fistIndex < 0)
        {
            fistIndex = 0;
        }
        for (int i = fistIndex; i < lastIndex; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }
        this.dlPaging.DataSource = dt;
        this.dlPaging.DataBind();
        if (dt.Rows.Count == 1 || dt.Rows.Count == 0)
            pldTrang.Visible = false;
        else
            pldTrang.Visible = true;
    }    

    private int CurrentPage
    {
        get
        {
            object objPage = ViewState["_CurrentPage"];
            int _CurrentPage = 0;
            if (objPage == null)
            {
                _CurrentPage = 0;
            }
            else
            {
                _CurrentPage = (int)objPage;
            }
            return _CurrentPage;
        }
        set { ViewState["_CurrentPage"] = value; }
    }

    private int fistIndex
    {
        get
        {
            int _FirstIndex = 0;
            if (ViewState["_FirstIndex"] == null)
            {
                _FirstIndex = 0;
            }
            else
            {
                _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
            }
            return _FirstIndex;
        }

        set { ViewState["_FirstIndex"] = value; }
    }

    private int lastIndex
    {
        get
        {
            int _LastIndex = 0;
            if (ViewState["_LastIndex"] == null)
            {
                _LastIndex = 0;
            }
            else
            {
                _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
            }
            return _LastIndex;
        }
        set { ViewState["_LastIndex"] = value; }
    }

    protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("Paging"))
        {
            CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
            this.databindTrackingDetail();

        }
    }

    protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
        lnkbtnPage.CommandArgument = (Convert.ToInt32(lnkbtnPage.Text) - 1).ToString();
        if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkbtnPage.Enabled = false;
            lnkbtnPage.Style.Add("fone-size", "14px");
            lnkbtnPage.Font.Bold = true;
        }
    }

    protected void lbFirst_Click(object sender, EventArgs e)
    {
        CurrentPage = 0;

        this.databindTrackingDetail();
    }

    protected void lbLast_Click(object sender, EventArgs e)
    {
        CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);

        this.databindTrackingDetail();
    }

    protected void lbPrev_Click(object sender, EventArgs e)
    {
        CurrentPage -= 1;

        this.databindTrackingDetail();
    }

    protected void lbNext_Click(object sender, EventArgs e)
    {
        CurrentPage += 1;

        this.databindTrackingDetail();
    }
    #endregion
}